package com.lwj.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lwj.entity.Content;
import com.lwj.entity.ContentCategory;
import com.lwj.service.IContentService;
import com.lwj.service.IContentCategoryService;
import com.lwj.util.PageResult;
import com.lwj.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lwj
 * @since 2025-01-15
 */
@RestController
@RequestMapping("/category")
public class ContentCategoryController {
	@Autowired
	private IContentCategoryService contentCategoryService;
	@Autowired
	private IContentService contentService;
	@GetMapping("/list")
	public R list(){
		return R.ok().data("list", contentCategoryService.list());
	}

	// 分页查询（不带条件）
	@GetMapping("/findByPage/{page}/{pageSize}")
	public R findByPage(@PathVariable("page") Integer page,
							 @PathVariable("pageSize") Integer pageSize) {
		PageResult<ContentCategory> pr = contentCategoryService.findByPage(page,pageSize);
		return R.ok().data("pr",pr);
	}
	// 分页查询（带条件）
	@PostMapping("/search/{page}/{pageSize}")
	public R search(@PathVariable("page") Integer page,
						 @PathVariable("pageSize") Integer pageSize,
						 @RequestBody Map<String,String> params){
		PageResult<ContentCategory> pr = contentCategoryService.search(page,pageSize,params.get("tname"));
		return R.ok().data("pr",pr);
	}

	// 添加
	@PostMapping("/add")
	public R add(@RequestBody ContentCategory contentCategory){
		boolean flag = contentCategoryService.save(contentCategory);
		return flag ? R.ok().message("添加成功了!欧耶") : R.error().message("添加失败!呜呜呜");
	}

	//修改
	@PutMapping("/update")
	public R update(@RequestBody ContentCategory contentCategory){
		boolean flag = contentCategoryService.updateById(contentCategory);
		return flag ? R.ok().message("修改成功啦欧耶！") : R.error().message("修改失败!呜呜呜");
	}



	@DeleteMapping("/delete/{ids}")
	public R delete(@PathVariable("ids") String ids){
		String[] temp = ids.split(",");
		List<String> list = Arrays.asList(temp);
		for(String id:list)
		{
			Wrapper<Content> wrapper = Wrappers
					.<Content>lambdaQuery()
					.eq(Content::getId, id);
			List<Content> contents = contentService.list(wrapper);
			if(!contents.isEmpty()) return R.error().message("删除失败!,有相关广告依赖该类型！");
		};
		return contentCategoryService.removeByIds(list) ? R.ok().message("删除成功!") : R.error().message("删除失败！");
	}
}
